package uc.patternlock;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import cn.onekit.CONFIG;
import cn.onekit.JSON;
import cn.onekit.MESSAGE;
import co.chuangdian.oflauncher.R;
import uc.MyApp;
import uc.PasswordType;
import uc.patternlock.LockPatternView.Cell;
import uc.patternlock.LockPatternView.DisplayMode;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 创建手势密码类
 * 
 * @author 手势密码创建
 * 
 */
public class CreateGesturePasswordActivity extends Activity {
	private static final int ID_EMPTY_MESSAGE = -1;
	private static final String KEY_UI_STAGE = "uiStage";
	private static final String KEY_PATTERN_CHOICE = "chosenPattern";
	/** 中间圆点解锁图案 **/

	protected TextView mHeaderText;
	protected List<LockPatternView.Cell> mChosenPattern = null;
	private Toast mToast;
	private Stage mUiStage = Stage.Introduction;

	private StringBuffer fBuffer = new StringBuffer();

	/**
	 * 底部左侧按钮
	 */
	enum LeftButtonMode {

		// 在不同状态下为按钮设置不同的文字
		// <Cancel-取消;CancelDisabled-禁用取消;Retry-重试;RetryDisabled-禁用重试;Gone-过去的>
		Cancel(android.R.string.cancel, true), CancelDisabled(android.R.string.cancel, false), Retry(R.string.app_name,
				true), RetryDisabled(R.string.app_name, false), Gone(ID_EMPTY_MESSAGE, false);
		/**
		 * @param text
		 *            指定显示文本的样式
		 * @param enabled
		 *            是否被启用
		 */
		LeftButtonMode(int text, boolean enabled) {
			this.text = text;
			this.enabled = enabled;
		}

		final int text;
		final boolean enabled;
	}

	/**
	 * 底部右侧按钮
	 */
	enum RightButtonMode {

		// 在不同状态下为按钮设置不同的文字
		// <Continue-继续;ContinueDisabled-禁用继续;Confirm-确认;ConfirmDisabled-禁用确认;Ok-搞定>
		Continue(R.string.app_name, true), ContinueDisabled(R.string.app_name, false), Confirm(R.string.app_name,
				true), ConfirmDisabled(R.string.app_name, false), Ok(android.R.string.ok, true);

		/**
		 * @param text
		 *            指定显示文本的样式
		 * @param enabled
		 *            是否被启用
		 */
		RightButtonMode(int text, boolean enabled) {
			this.text = text;
			this.enabled = enabled;
		}

		final int text;
		final boolean enabled;
	}

	/**
	 * 用户根据需要选择对应状态 受保护的枚举类(作用范围-当前包类,不含子类)
	 */
	protected enum Stage {

		// 根据状态不同启用按钮
		// <Introduction-初步绘制;HelpScreen-帮助屏幕;ChoiceTooShort-选择太短;FirstChoiceValid-首次选择有效;
		// NeedToConfirm-再次确认;ChoiceConfirmed-选择确认>
		Introduction(R.string.setting_lockscreen_password_pattern_header, LeftButtonMode.Cancel,
				RightButtonMode.ContinueDisabled, ID_EMPTY_MESSAGE, true),

		ChoiceTooShort(R.string.setting_lockscreen_password_pattern_short, LeftButtonMode.Retry,
				RightButtonMode.ContinueDisabled, ID_EMPTY_MESSAGE, true),

		FirstChoiceValid(R.string.setting_lockscreen_password_pattern_save, LeftButtonMode.Retry,
				RightButtonMode.Continue, ID_EMPTY_MESSAGE, false),

		NeedToConfirm(R.string.setting_lockscreen_password_pattern_confirm, LeftButtonMode.Cancel,
				RightButtonMode.ConfirmDisabled, ID_EMPTY_MESSAGE, true),

		ConfirmWrong(R.string.setting_lockscreen_password_pattern_wrong, LeftButtonMode.Cancel,
				RightButtonMode.ConfirmDisabled, ID_EMPTY_MESSAGE, true),

		ChoiceConfirmed(R.string.setting_lockscreen_password_patteern_sureheader, LeftButtonMode.Cancel,
				RightButtonMode.Confirm, ID_EMPTY_MESSAGE, false),

		// 4-28 HHA
				Login(R.string.setting_lockscreen_password_input_pwd, LeftButtonMode.Cancel, RightButtonMode.Confirm,
						ID_EMPTY_MESSAGE, false);

		Stage(int headerMessage, LeftButtonMode leftMode, RightButtonMode rightMode, int footerMessage,
				boolean patternEnabled) {
			this.headerMessage = headerMessage;
			this.leftMode = leftMode;
			this.rightMode = rightMode;
			this.footerMessage = footerMessage;
			this.patternEnabled = patternEnabled;
		}

		final int headerMessage;
		final LeftButtonMode leftMode;
		final RightButtonMode rightMode;
		final int footerMessage;
		final boolean patternEnabled;
	}

	/**
	 * 弹出提示信息
	 * 
	 * @param message
	 */
	private void showToast(CharSequence message) {

		if (null == mToast) {
			mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(message);
		}

		mToast.show();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_password_patterncreate);

		mLockPatternView = (LockPatternView) findViewById(R.id.gesturepwd_create_lockview);
		mHeaderText = (TextView) findViewById(R.id.gesturepwd_create_text);
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		mLockPatternView.setTactileFeedbackEnabled(true);

		if (savedInstanceState == null) {// 如果为空
			// 启用帮助模式
			updateStage(Stage.Introduction);
			// updateStage(Stage.HelpScreen);
		} else {// 如果存在实例
			// 读取保存的状态
			final String patternString = savedInstanceState.getString(KEY_PATTERN_CHOICE);
			if (patternString != null) {// 如果读取结果不为空
				// 直接进入对应状态-解密
				mChosenPattern = LockPatternUtils.stringToPattern(patternString);
			}
			updateStage(Stage.values()[savedInstanceState.getInt(KEY_UI_STAGE)]);
		}

	}

	/**
	 * 通知清除中间区域图案
	 */
	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
		}
	};

	/**
	 * 监听中部区域所处模式,做出相关动作
	 */
	protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

		/**
		 * 开始模式
		 */
		public void onPatternStart() {
			// 删除回调
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();// 开始设置密码阶段提示用户
		}

		/**
		 * 清除模式
		 */
		public void onPatternCleared() {
			// mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		/**
		 * 检测模式
		 */
		public void onPatternDetected(List<LockPatternView.Cell> pattern) {
			if (pattern == null)
				return;
			// 根据不同杰作做出反应
			if (mUiStage == Stage.NeedToConfirm || mUiStage == Stage.ConfirmWrong) {
				if (mChosenPattern == null)
					throw new IllegalStateException("null chosen pattern in stage 'need to confirm");
				if (mChosenPattern.equals(pattern)) {
					updateStage(Stage.ChoiceConfirmed);
				} else {
					updateStage(Stage.ConfirmWrong);
				}
			} else if (mUiStage == Stage.Introduction || mUiStage == Stage.ChoiceTooShort) {
				if (pattern.size() < LockPatternUtils.MIN_LOCK_PATTERN_SIZE) {
					updateStage(Stage.ChoiceTooShort);
				} else {
					mChosenPattern = new ArrayList<LockPatternView.Cell>(pattern);
					updateStage(Stage.FirstChoiceValid);
				}
			} else {
				throw new IllegalStateException("Unexpected stage " + mUiStage + " when " + "entering the pattern.");
			}
		}

		public void onPatternCellAdded(List<Cell> pattern) {

		}

		/**
		 * 设置密码阶段提示用户<同时禁用底部按钮>
		 */
		private void patternInProgress() {
			mHeaderText.setText(R.string.setting_lockscreen_password_pattern_inprogress);

		}
	};
	private LockPatternView mLockPatternView;

	/**
	 * 更新阶段
	 * 
	 * @param stage
	 */
	@SuppressWarnings("incomplete-switch")
	private void updateStage(Stage stage) {
		mUiStage = stage;
		if (stage == Stage.ChoiceTooShort) {
			mHeaderText.setText(getResources().getString(stage.headerMessage, LockPatternUtils.MIN_LOCK_PATTERN_SIZE));
		} else {
			mHeaderText.setText(stage.headerMessage);
		}

		if (stage.patternEnabled) {
			mLockPatternView.enableInput();
		} else {
			mLockPatternView.disableInput();
		}

		mLockPatternView.setDisplayMode(DisplayMode.Correct);

		switch (mUiStage) {
		// case Introduction:// 引用阶段
		// mLockPatternView.clearPattern();
		// break;
		// case HelpScreen:// 帮助阶段
		// mLockPatternView.setPattern(DisplayMode.Animate, mAnimatePattern);
		// break;
		case ChoiceTooShort:// 选择长度过短阶段
			mLockPatternView.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case FirstChoiceValid:// 第一次设置阶段
			updateStage(Stage.NeedToConfirm);
			break;
		case NeedToConfirm:// 第二次设置阶段
			mLockPatternView.clearPattern();
			// updatePreviewViews();
			break;
		case ConfirmWrong:// 第二次出错阶段
			mLockPatternView.setDisplayMode(DisplayMode.Wrong);
			postClearPatternRunnable();
			break;
		case ChoiceConfirmed:// 确认阶段
			saveChosenPatternAndFinish();
			break;
		}

	}

	/**
	 * 清除错误的花样,除非已经开始绘制新的图样
	 */
	private void postClearPatternRunnable() {
		mLockPatternView.removeCallbacks(mClearPatternRunnable);
		mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
	}

	/**
	 * 密码设置完成
	 */
	private void saveChosenPatternAndFinish() {
		// hha --解除了注释
		// App.getInstance().getLockPatternUtils().saveLockPattern(mChosenPattern);

		MyApp.getInstance().getLockPatternUtils().saveLockPattern(mChosenPattern);
		// CONFIG.set("password", fBuffer.toString());
		showToast("密码设置成功");
		try {

			String settingstring = (String) CONFIG.get("setting");
			JSONObject setting = JSON.parse(settingstring);
			JSONObject lockscreen = setting.optJSONObject("lockscreen");
			// password_number.put("number", fBuffer.toString());

			// 设置password_type 进去setting
			lockscreen.put("password_type", PasswordType.pattern.ordinal());
			setting.put("lockscreen", lockscreen);
			CONFIG.set("setting", setting);
			// CONFIG.set("password", fBuffer.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		MESSAGE.send("setting_password_type", null, null);
		finish();
		// startActivity(new Intent(this, LockScreen_PasswordActivity.class));
		// finish();
	}

	public static void gotoActivity(Activity opener, int type) {
		// 创建意图Intent对象
		Intent intent = new Intent(opener, CreateGesturePasswordActivity.class);
		intent.putExtra("type", type);// 传递值
		opener.startActivity(intent);// 界面跳转
	}
}
